package com.ynny.jdbc02;


import com.mysql.cj.jdbc.Driver;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtils {
    public static final String URL = "jdbc:mysql://localhost:3306/db01";
    public static final String USER_NAME = "root";
    public static final String PWD = "root";


    static ResultSet resultSet;

    static PreparedStatement preparedStatement;

    static Connection connection;
    /**
     * 1.获取连接
     * 2.查询所有的方法
     * 3.关闭
     */
    private static Connection getConnection(){
        try {
/*            //1.创建驱动
            Driver driver = new Driver();
            //2.注册驱动
            DriverManager.registerDriver(driver);*/
            //3.获取连接
            return DriverManager.getConnection(URL,USER_NAME,PWD);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    public static List<Map<String,Object>> selectAllData(String sql,
                                                         Object[] params) throws SQLException {
        //获取连接
        connection = getConnection();

        //获得运输sql的工具


         preparedStatement = connection
                .prepareStatement(sql);

        //占位符赋值

        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1 ,
                    params[i]);
        }




        //执行sql
         resultSet = preparedStatement.executeQuery();


        //解析  获取整个表格的原数据
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();

        ArrayList<Map<String,Object>> list = new ArrayList<>();



        while (resultSet.next()){

            HashMap<String, Object> map = new HashMap<>();
            for (int i = 0; i < columnCount; i++) {

                String key = metaData.getColumnName(i + 1);
                String value = resultSet.getString(key);

                map.put(key,value);

            }

            list.add(map);

        }


        return list;
    }


    public static void close() throws SQLException {

        resultSet.close();
        preparedStatement.close();
        connection.close();


    }


}
